package com.jianye.recycdona.model.fragment;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.jianye.recycdona.R;
import com.jianye.recycdona.comm.BaseFragment;
import com.jianye.recycdona.control.bean.CommoditOrder;
import com.jianye.recycdona.control.bean.Credits;
import com.jianye.recycdona.control.http.CommoditOrderHttp;
import com.jianye.recycdona.control.http.CreaditsHttp;
import com.jianye.recycdona.control.http.UserOkHttp;
import com.jianye.recycdona.model.fragment.wlfare.ViewPagerForScrollView;
import com.jianye.recycdona.model.fragment.wlfare.WlfareAllFragment;
import com.jianye.recycdona.model.fragment.wlfare.WlfareFoodFragment;
import com.jianye.recycdona.model.fragment.wlfare.WlfareKitchenFragment;
import com.jianye.recycdona.model.fragment.wlfare.WlfareLifeFragment;
import com.jianye.recycdona.model.fragment.wlfare.WlfareWashkFragment;
import com.jianye.recycdona.model.fragment.wlfare.adapter.CreditsAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.content.Context.MODE_PRIVATE;


public class WelfareFragment extends BaseFragment {

    private View view;

    TextView walfare_point;
    ListView walfare_listview_credits;
    List<Credits.ContentBean> contentBeans;
    CreditsAdapter creditsAdapter;
    private SmartRefreshLayout refreshLayout;
    public static WelfareFragment wlfareFragment=new WelfareFragment();
    private SharedPreferences sp;

    public static WelfareFragment getWlfareFragment() {
        return wlfareFragment;
    }

    private  WlfareAllFragment  wlfareAllFragment=new WlfareAllFragment();
    private  WlfareFoodFragment  wlfareFoodFragment=new WlfareFoodFragment();
    private  WlfareWashkFragment wlfareWashkFragment=new WlfareWashkFragment();
    private  WlfareKitchenFragment  wlfareKitchenFragment=new WlfareKitchenFragment();
    private  WlfareLifeFragment wlfareLifeFragment=new WlfareLifeFragment();


    TextView mDic_all;
    TextView mDicOne;
    TextView mDicTwo;
    TextView mDicThree;
    TextView mDicFoun;
    ViewPagerForScrollView viewPager;

    public List<CommoditOrder.ContentBean> commdity=new ArrayList<>();

    public static WelfareFragment newInstance(String info) {
        Bundle args = new Bundle();
        WelfareFragment fragment = new WelfareFragment();
        args.putString("info", info);
        fragment.setArguments(args);
        return fragment;
    }

    public List<CommoditOrder.ContentBean> getCommdity() {

        if (commdity.size()<=0){
            initcommodity();//刷新商品数据
        }
        return commdity;
    }


    public List<CommoditOrder.ContentBean> initcommodity() {
        try {
            commdity = CommoditOrderHttp.getMyOkHttp().getCommoditOrder();
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }

        return commdity;
    }


    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if (view==null){
            view = inflater.inflate(R.layout.fragment_wlfare, container, false);
        }

        sp =getContext().getSharedPreferences("config", MODE_PRIVATE);//confi 文件名


        initfindView();
        setPoint();
        updata();
        ViewPagetInit();
        return view;
    }

    @SuppressLint("SetTextI18n")
    private void setPoint() {
        //设置积分
        int point=sp.getInt("point",0);
        walfare_point=view.findViewById(R.id.walfare_point);
        walfare_point.setText("积分:"+point+"颗");
    }

    //下拉刷新
    private void updata() {
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

                Toast.makeText(getContext(),"已经到底了",Toast.LENGTH_LONG).show();
                refreshLayout.finishLoadMore();//结束加载
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                int viewpage=viewPager.getCurrentItem();//获取当前fragment位置


                //刷新商品数据
                initcommodity();
                if (viewpage==0){
                    wlfareAllFragment.initFindviewId(initcommodity());
                }

                //厨卫
                if (viewpage==1){
                    wlfareKitchenFragment.initFindviewId(initcommodity());
                }
                //食品
                if (viewpage==2){
                    wlfareFoodFragment.initFindviewId(initcommodity());
                }
                //洗护
                if (viewpage==3){
                    wlfareWashkFragment.initFindviewId(initcommodity());
                }
                //居家
                if (viewpage==4){
                    wlfareLifeFragment.initFindviewId(initcommodity());
                }

                initCredits();
                //刷新积分
                try {
                    String phone=sp.getString("phone","");
                    UserOkHttp.getMyOkHttp().getUserinfo(phone,sp);
                } catch (ExecutionException | InterruptedException e) {
                    e.printStackTrace();
                }

                setPoint();

                Toast.makeText(getContext(),"刷新成功",Toast.LENGTH_LONG).show();
                refreshLayout.finishRefresh();//结束刷新
            }


        });
    }


    //初始化数据
    @SuppressLint("SetTextI18n")
    private void initfindView() {


        viewPager=view.findViewById(R.id.wlafare_main);

        refreshLayout=view.findViewById(R.id.credits_refreshLayout);

        initCredits();
        initcommodity();//刷新商品数据

    }


    //初始化积分配置
    private void initCredits() {
        //积分listview
        contentBeans=new ArrayList<>();
        walfare_listview_credits=view.findViewById(R.id.walfare_listview_credits);
        try {
            contentBeans= CreaditsHttp.getMyOkHttp().getCredits();
            Log.d("creditysdata", "initCredits:"+contentBeans.get(1).getPath());
            creditsAdapter=new CreditsAdapter(contentBeans,getContext());
            walfare_listview_credits.setAdapter(creditsAdapter);
            setListViewHeightBasedOnChildren(walfare_listview_credits);
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }
    }
    //重置指示器颜色
    private void resetBackground()
    {    mDic_all.setBackgroundResource(R.color.white);
        mDicOne.setBackgroundResource(R.color.white);
        mDicThree.setBackgroundResource(R.color.white);
        mDicTwo.setBackgroundResource(R.color.white);
        mDicFoun.setBackgroundResource(R.color.white);
    }
    /**
     * findfragment页面初始化
     * viewPager滑动事件监听
     */
    private void ViewPagetInit() {

        mDic_all=view.findViewById(R.id.wlfare_dic_allline);

        mDicOne=view.findViewById(R.id.wlfare_dic_oneline);

        mDicTwo=view.findViewById(R.id.walfare_dic_twoline);

        mDicThree=view.findViewById(R.id.walfare_dic_threeline);

        mDicFoun=view.findViewById(R.id.walfare_dic_founline);

        viewPager=view.findViewById(R.id.wlafare_main);

        ButterKnife.bind(this, view);
        CreditsFragementAdapter creditsAdapter = new CreditsFragementAdapter(getChildFragmentManager());
        viewPager.setOffscreenPageLimit(1);
        viewPager.setAdapter(creditsAdapter);

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                resetBackground();
                switch (position)
                {
                    case 0:
                        mDic_all.setBackgroundResource(R.color.blue);
                        break;
                    case 1:
                        mDicOne.setBackgroundResource(R.color.blue);
                        break;
                    case 2:
                        mDicTwo.setBackgroundResource(R.color.blue);
                        break;
                    case 3:
                        mDicThree.setBackgroundResource(R.color.blue);
                        break;
                    case  4:
                        mDicFoun.setBackgroundResource(R.color.blue);
                        break;
                    default:
                        break;
                }
            }
            @SuppressLint({"NonConstantResourceId", "ResourceAsColor"})
            @Override
            public void onPageScrollStateChanged(int state) {

                switch (view.getId())
                {
                    case R.id.walfare_all:
                        mDic_all.setBackgroundResource(R.color.blue);
                        break;
                    case R.id.walfare_one:
                        mDicOne.setBackgroundResource(R.color.blue);
                        break;

                    case R.id.walfare_two:
                        mDicTwo.setBackgroundResource(R.color.blue);
                        break;

                    case R.id.walfare_three:
                        mDicThree.setBackgroundResource(R.color.blue);
                        break;

                    case R.id.walfare_foun:
                        mDicFoun.setBackgroundResource(R.color.blue);
                        break;

                    default:
                        break;
                }
            }
        });
    }

    @SuppressLint({"ResourceAsColor", "NonConstantResourceId"})
    @OnClick({R.id.walfare_all,R.id.walfare_one, R.id.walfare_two, R.id.walfare_three,R.id.walfare_foun})
    public void onViewClicked(View view)
    {
        resetBackground();
        switch (view.getId())
        {

            case R.id.walfare_all:
                mDic_all.setBackgroundResource(R.color.blue);
                viewPager.setCurrentItem(0);
                break;
            case R.id.walfare_one:
                mDicOne.setBackgroundResource(R.color.blue);
//                mDicOne.setTextColor(R.color.black1);
                viewPager.setCurrentItem(1);
                break;
            case R.id.walfare_two:
                mDicTwo.setBackgroundResource(R.color.blue);
//                mDicTwo.setTextColor(R.color.black1);
                viewPager.setCurrentItem(2);
                break;
            case R.id.walfare_three:
                mDicThree.setBackgroundResource(R.color.blue);
//                mDicThree.setTextColor(R.color.black1);
                viewPager.setCurrentItem(3);
                break;
            case R.id.walfare_foun:
                mDicFoun.setBackgroundResource(R.color.blue);
//                mDicFoun.setTextColor(R.color.black1);
                viewPager.setCurrentItem(4);
                break;
            default:
                break;
        }
    }

    //统计ListView的高度
    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }






    private class CreditsFragementAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mList =new ArrayList<>();

        public CreditsFragementAdapter(@NonNull FragmentManager fm) {
            super(fm);
            mList.add(wlfareAllFragment);
            mList.add(wlfareKitchenFragment);//厨卫
            mList.add(wlfareFoodFragment);//食品
            mList.add(wlfareWashkFragment);//洗护
            mList.add(wlfareLifeFragment);//居家
        }


        @NonNull
        @Override
        public Fragment getItem(int position) {
            return mList.get(position);
        }

        @Override
        public int getCount() {
            return mList.size();
        }
    }
}